package com.sdhs.paas.gateway.util;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriComponentsBuilder;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.sdhs.paas.gateway.filter.AdminAuthenticationFilter;
import com.sdhs.paas.gateway.model.PaasBeanObject;
import com.sdhs.paas.sdk.core.PaasBaseResponse;
import com.sdhs.paas.sdk.core.logger.Logger;
import com.sdhs.paas.sdk.core.logger.LoggerFactory;
import com.sdhs.paas.sdk.core.web.client.PaasRestTemplate;

@Component
public class RestTemplateUtil
{
  private static Logger logger = LoggerFactory.getLogger(AdminAuthenticationFilter.class);

  public static String parseUrl(String url, String userId)
  {

    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
    String uri = builder.build().expand(userId).encode().toString();
    return uri;
  }

  public static Object get(String url, String userId)
  {
    String uri = parseUrl(url, userId);
    PaasRestTemplate paasRestTemplate = (PaasRestTemplate)SpringContextUtil.getBean("externalRestTemplate");
    ResponseEntity response = paasRestTemplate.getForEntity(uri, String.class);
    ResponseEntity<PaasBaseResponse<PaasBeanObject>> result = paasRestTemplate.exchange(
    		uri,
            HttpMethod.GET,
            HttpEntity.EMPTY,
            new ParameterizedTypeReference<PaasBaseResponse<PaasBeanObject>>() {
            });
    String jsonStr = String.valueOf(result.getBody().getBody().getContent());
    if(StringUtils.isEmpty(jsonStr)){
    	return null;
    }
    Map<String,Object> map = JSON.parseObject(jsonStr, new TypeReference<Map<String,Object>>(){});
    return map;
//    List<Map<String,Object>> resourceList = (List<Map<String, Object>>) map.get("policyData");
//    PaasBeanObject paasBeanObject = JSON.parseObject((String)response.getBody(), new TypeReference<PaasBeanObject>(){});
//    System.out.println(paasBeanObject.getContent());
//    return ((PaasBeanObject)map.get("body")).getContent();
  }
}